package com.aabte.spring.validator;

import com.aabte.spring.validator.customize.Update;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import javax.validation.constraints.NotNull;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/4/25
 */
@Validated
@RestController
@RequestMapping(path = "/user")
public class UserController {

  @GetMapping("/get")
  public RspDTO<UserDTO> getUser(
      @RequestParam("userId") @NotNull(message = "用户id不能为空") Long userId) {
    UserDTO user = selectById(userId);
    if (user == null) {
      return RspDTO.nonAbsent("用户不存在");
    }
    return RspDTO.success(user);
  }

  private UserDTO selectById(Long userId) {
    return null;
  }

  @PostMapping(path = "/save/serial")
  public Object save(@RequestBody UserDTO userDTO) {
    String mobile = userDTO.getMobile();
    //手动逐个 参数校验~ 写法
    if (StringUtils.isBlank(mobile)) {
      return RspDTO.paramFail("mobile:手机号码不能为空");
    } else if (!Pattern.matches("^[1][3,4,5,6,7,8,9][0-9]{9}$", mobile)) {
      return RspDTO.paramFail("mobile:手机号码格式不对");
    }

    //抛出自定义异常等~写法
    if (StringUtils.isBlank(userDTO.getUsername())) {
      throw new BizException(Constant.PARAM_FAIL_CODE, "用户名不能为空");
    }

    // 比如写一个map返回
    if (StringUtils.isBlank(userDTO.getSex())) {
      Map<String, Object> result = new HashMap<>(5);
      result.put("code", Constant.PARAM_FAIL_CODE);
      result.put("msg", "性别不能为空");
      return result;
    }
    //.........各种写法 ...
    // userService.save(userDTO);
    return RspDTO.success();
  }


  @PostMapping("/save/valid")
  public RspDTO saveValid(@RequestBody @Validated UserDTO userDTO) {
    // userService.save(userDTO);
    return RspDTO.success();
  }

  @PostMapping(path = "/update/groups")
  public RspDTO update(@RequestBody @Validated(Update.class) UserDTO userDTO) {
    // userService.update(userDTO);
    return RspDTO.success();
  }

}
